﻿using AdminBase.Model;

namespace AdminBase.Common.Helpers
{
    public class TreeDataHelper
    {

        /// <summary>
        /// 获取树形数据
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public static List<TreeDto> GetTreeData<T>(List<T> list) where T : TreeBase
        {
            // 从一级开始往下找子级
            List<TreeDto> newlist = list.Where(p => p.ParentID == 0 || p.ParentID == null)
                .Select(p => new TreeDto()
                {
                    ID = p.ID,
                    Label = p.Name,
                }).ToList();
            // 通过递归获取子级
            GetChildren(list, newlist);
            return newlist;
        }

        /// <summary>
        /// 递归获取子级
        /// </summary>
        /// <param name="all">所有数据，作为基础数据</param>
        /// <param name="res">结果数据</param>
        public static void GetChildren<T>(List<T> all, List<TreeDto> res) where T : TreeBase
        {
            if (res != null && res.Count > 0)
            {
                res.ForEach(item =>
                {
                    var child = all.Where(p => p.ParentID == item.ID)
                    .Select(p => new TreeDto()
                    {
                        ID = p.ID,
                        Label = p.Name,
                    }).ToList();

                    if (child != null && child.Count > 0)
                    {
                        item.Children = child;
                        GetChildren(all, child);
                    }
                });
            }
        }
    }
}
